package com.lbkj.ops.controller;

import com.github.wenhao.jpa.Specifications;
import com.lbkj.ops.common.exception.Http404Exception;
import com.lbkj.ops.common.jpa.JpaBaseEntity;
import com.lbkj.ops.common.util.CuxBeanUtils;
import com.lbkj.ops.dao.OpsServerDao;
import com.lbkj.ops.model.OpsServer;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/bpi/servers")
public class ServerController {

    @Autowired
    private OpsServerDao dao;

    @GetMapping
    public Page<OpsServer> list(@RequestParam(required = false, defaultValue = "1") Integer page,
                                @RequestParam(required = false, defaultValue = "15") Integer size,
                                String name) {
        Specification<OpsServer> specification = Specifications.<OpsServer>and()
                .like(StringUtils.isNotBlank(name), "name", "%" + name + "%")
                .build();
        PageRequest pageRequest = PageRequest.of(page-1, size, Sort.by(Sort.Order.desc(JpaBaseEntity.UPDATE_TIME)));
        return dao.findAll(specification, pageRequest);
    }

    @PostMapping
    public void save(@RequestBody OpsServer data) {
        Long id = data.getId();
        if(id != null) {
            OpsServer raw = dao.findById(data.getId()).orElseThrow(Http404Exception::new);
            CuxBeanUtils.copyPropertiesIgnoreNull(data, raw);
            dao.save(raw);
        } else {
            dao.save(data);
        }
    }

    @DeleteMapping("/{id}")
    public void delete(@PathVariable Long id) {
        OpsServer raw = dao.findById(id).orElseThrow(Http404Exception::new);
        dao.delete(raw);
    }




}
